package com.minisoft.pingan;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author JueSu
 * @description: TODO
 * @date 2023/12/10 12:23
 */
public class ExportBdUrl {

    static String bodyStr = "{\n" +
            "    \"vehicleLicenceCode\": \"\",\n" +
            "    \"queryDateBegin\": \"2023-12-01\",\n" +
            "    \"queryDateEnd\": \"2023-12-05\",\n" +
            "    \"vehicleFrameNo\": \"\",\n" +
            "    \"page\": 1,\n" +
            "    \"rows\": 100,\n" +
            "    \"applicantType\": \"\",\n" +
            "    \"coinsuranceMark\": \"\",\n" +
            "    \"productCode\": \"\",\n" +
            "    \"carBusinessType\": \"\",\n" +
            "    \"taskState\": \"B5\",\n" +
            "    \"subTaskState\": \"\",\n" +
            "    \"personnelAttribute\": \"2\",\n" +
            "    \"applicantName\": \"\",\n" +
            "    \"isProduct\": \"isProduct\",\n" +
            "    \"saleAgentCode\": \"2040006831\",\n" +
            "    \"departmentCode\": \"204151007\",\n" +
            "    \"lowDepartment\": true,\n" +
            "    \"applySeletemodel\": \"0\",\n" +
            "    \"userId\": \"EX-PANTANGMEI488\"\n" +
            "}";
    /**
     * 只需要修改Cookie，url (qtWaitTaskInfopai65o)
     */
    static String Cookie = "SESSION=MjZhYjJmMGYtMDA2Yi00YThjLTgzMDQtYjkxODg4ZGJmOGY5; DT_E_ID=%7B%22url%22%3A%22https%3A%2F%2Ficorepnbs.pingan.com.cn%2Ficore_pnbs%2Findex.html%3Fv%3DICORE-IBCS-AUTO1.2024.0904.950790%26t%3D1725786890534%22%2C%22referer%22%3A%22https%3A%2F%2Ficorepnbs.pingan.com.cn%2Ficore_pnbs%2Fdo%2Fusermanage%2FsystemTransfer%22%7D; DT_C_ID=a697cddac363b300-a2f95dc2e550e536-1727003176430-1727003176430; us=stable_759; routeopr=40611357cd965b27797134997cf8abfc; PA_GREY=EX-LIYE879; BIGipServerPOOL_PACLOUD_PRDR20230106232593=2072218583.5162.0000; v1LIHNTx4qTOO=5f_32Ok7vVcHFWXrLKSAqUbWG4kroFhfpYOCzvspU7YjOCmW_SALbMqU1Ebw0iwfEbg4zDt6rwVC_sv9x0QEOLa; BIGipServerPOOL_PACLOUD_PRDR2019112805992=1210229207.33420.0000; USER_REDIS_COOKIE=RVgtTElZRTg3OTE3Mjg4NzUwOTQ2MDQtNTkwNzEwNDc1XzE3Mjg4NzUwOTkzNzc%3D; v1LIHNTx4qTOP=HEIO9I7sx_CTHJk9Xzy2_IVhNws3Qo8X3EJ4RsOEI5QXZ0k13lumQR.x8WrnWMR5ihMOuWS43PtJNDYRPZZqTqMKbNI6r7vp6seTeWcDQzZxvNpgq1r.RVnsa4eiGkuQTJPu5xx2nvgrQbjzMeCCtHbswlKQp6IqNLZGyN_Fl_xBx0r4Cf3fO2WLvAJhlFZiKk9b0NmMhDOJ0ox5ELM07ejSJCwUABgCtJK.p2LgkNMlT9tCcbjCEbCzzfq.sI_vZesQcbximDKcw0Dp.b3tEVMxQIHDADqViF5.pjoBHXQE6ju2yPdP31avfUxVd8ZDYP2L9hSpyr01un3gznWDcNDY2N06CuUFEXIxyNXKVbC1O6yfzYxJyZXb2cn3zbAZhNHdJeZlrYEl5vLWJn7FxG";
    static String url = "https://icorepnbs.pingan.com.cn/icore_pnbs/do/app/workbench/qtWaitTaskInfopai65o?fhiUFUxo=5IsOzalqErH_rSi5K72mDOnSCT_aDmNnwBgzr1AYCubLcsvnHFhtEE_u8Qw654x187kPUcHBfhWwWOBrlSqWSGkfD2cY3.fA";
    /**
     * 如果要过滤指定的业务员
     */
    static String inputByIdFilter = "";


    @Data
    static class BaoDan {
        String dateInput;//日期
        String inputById;//录单人
        String applicantName;//投保人
        String insuredName;//被保人
        String shangYeXian;//商业险
        String vehicleLicenceCode;//车牌号
        String jiaoQiangXian;//交强险
        String yiWaiXian;//意外险

        public List<Object> toRow() {
            return ListUtil.of(dateInput,vehicleLicenceCode,shangYeXian,jiaoQiangXian,yiWaiXian,applicantName,insuredName,inputById);
        }
    }

    static Map<String,BaoDan> baoDanMap = new HashMap<>();
    private static List<BaoDan> getBaodanList(String begin,String end) {

        JSONObject body = JSON.parseObject(bodyStr);
        body.put("queryDateBegin",begin);
        body.put("queryDateEnd",end);
        int page = 1;
        JSONObject jsonObj = getDatalist(page,body);
        JSONArray datalist = jsonObj.getJSONArray("datalist");
        int totalPageSize = jsonObj.getInteger("pageSize");
        List<BaoDan> result = new ArrayList<>();
        while (CollUtil.isNotEmpty(datalist)) {
            for (Object o : datalist) {
                JSONObject obj = (JSONObject) o;
                String vehicleLicenceCode = obj.getString("vehicleLicenceCode");
                String inputById = obj.getString("inputById");
                if (vehicleLicenceCode == null) {
                    continue;
                }
                //过滤指定人
                if (StrUtil.isNotBlank(inputByIdFilter) && !inputByIdFilter.contains(inputById)) {
                    continue;
                }
                BaoDan baoDan = baoDanMap.get(vehicleLicenceCode);
                if (baoDan == null) {
                    baoDan = new BaoDan();
                    baoDan.setInputById(inputById);
                    baoDan.setDateInput(obj.getString("dateInput"));
                    baoDan.setInsuredName(obj.getString("insuredName"));
                    baoDan.setApplicantName(obj.getString("applicantName"));
                    baoDan.setVehicleLicenceCode(vehicleLicenceCode);
                    baoDanMap.put(vehicleLicenceCode,baoDan);
                }
                String techProduct = obj.getString("techProduct");
                String totalActualPremium = obj.getString("totalActualPremium");
                if (techProduct != null) {
                    if ("TP0100001".equals(techProduct)) {
                        baoDan.setShangYeXian(totalActualPremium);
                    } else {
                        baoDan.setJiaoQiangXian(totalActualPremium);
                    }
                } else {
                    baoDan.setYiWaiXian(totalActualPremium);
                }
            }
            //如果是最后一页，则退出
            if (page >= totalPageSize) {
                break;
            }
            page++;
            jsonObj = getDatalist(page,body);
            datalist = jsonObj.getJSONArray("datalist");
        }

        return result;
    }

    private static JSONObject getDatalist(int page,JSONObject body) {
        ThreadUtil.sleep(500);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Cookie",Cookie);
        headerMap.put("Referer","https://icorepnbs.pingan.com.cn/icore_pnbs/templates/apply_track_new.html?_v=1.2024.0528.27154817179942879661717994288089");
        body.put("page",page);
        Console.log("queryDateBegin={},queryDateEnd={},page={}",body.getString("queryDateBegin"),body.getString("queryDateEnd"),page);
        String jsonData = HttpUtil.createPost(url).headerMap(headerMap, true).body(body.toString()).execute().body();
        Console.log(jsonData);
        JSONObject jsonObject = JSON.parseObject(jsonData);
        return jsonObject;
    }

    public static LocalDate[][] generateDateRange(int year, int mon,int intervalDays) {
        List<LocalDate[]> dateRanges = new ArrayList<>();
        LocalDate startDate = LocalDate.of(year, mon, 1);
        //导一个月的数据
        LocalDate endDate = startDate.plusMonths(1); // 假设我们想要包含整年
        //导自定义结束日期
//        LocalDate endDate = LocalDate.of(2024, 1, 1); // 假设我们想要包含整年

        while (startDate.isBefore(endDate)) {
            LocalDate endDateInRange = startDate.plusDays(intervalDays - 1);
            if (!endDateInRange.isBefore(endDate)) {
                endDateInRange = endDate.plusDays(-1);
            }
            dateRanges.add(new LocalDate[]{startDate, endDateInRange});
            startDate = startDate.plusDays(intervalDays);
        }

        return dateRanges.toArray(new LocalDate[0][]);
    }

    //解释Curl 的url 和 cookie
    public static void parseCurl() {
        String curlCommand = FileUtil.readUtf8String(ExportBdUrl.class.getResource("/curl.txt").getFile());
        // 解析URL
        Pattern urlPattern = Pattern.compile("curl\\s+'(.*?)'");
        Matcher urlMatcher = urlPattern.matcher(curlCommand);
        if (urlMatcher.find()) {
            System.out.println("URL: " + urlMatcher.group(1));
            url = urlMatcher.group(1);
        }
        // 解析Cookie
        Pattern cookiePattern = Pattern.compile("-H\\s+'Cookie:\\s*(.*?)'");
        Matcher cookieMatcher = cookiePattern.matcher(curlCommand);
        if (cookieMatcher.find()) {
            System.out.println("Cookie: " + cookieMatcher.group(1));
            Cookie = cookieMatcher.group(1);
        }
    }
    //复制 qtWaitTaskInfopai65o 请求的 curl 命令就可以了
    public static void main(String[] args) {
        parseCurl();
        //获取当前日期前一个月的年和月
        LocalDate now = LocalDate.now();
        LocalDate lastMonth = now.minusMonths(1);
        Console.log("lastYea={},lastMonth={}",lastMonth.getYear(),lastMonth.getMonthValue());

        //23-4-9 23-9-24-1  24-1-6
        LocalDate[][] localDates = generateDateRange(lastMonth.getYear(), lastMonth.getMonthValue(),5);
        for (LocalDate[] localDate : localDates) {
            getBaodanList(localDate[0].toString(),localDate[1].toString());
            ThreadUtil.sleep(1000);
        }

        String outputFilePath = "D:\\网点汇总\\bake/baodanResult-"+ DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN) +".xlsx";
        List<String> columnList = ListUtil.toList("日期","车牌号","商业险","交强险","意外险","投保人","被保人","出单员id");

        List<List<Object>> rows = new ArrayList<>();
        Collection<BaoDan> baoDans = baoDanMap.values();
        for (BaoDan baoDan : baoDans) {
            rows.add(baoDan.toRow());
        }
        // Create Excel writer
        ExcelWriter writer = ExcelUtil.getWriter(outputFilePath);

        // Set the header row
        writer.writeHeadRow(columnList);

        // Write data rows
        writer.write(rows);

        // Close the writer and save the Excel file
        writer.close();

        System.out.println("done");
    }
}
